package com.zyq.config;

import com.alibaba.fastjson.JSON;
import com.zyq.common.vo.Result;
import com.zyq.service.impl.MyUserService;
import com.zyq.common.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
public class MySpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserService myUserService;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    // 重写父类的两个方法，第一个是得到username获取到这个用户的全部信息以及权限
    // 第二个是 过滤器链，进行放行登录路径，已经登录成功或失败的返回JSON数据

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 传递用户名和密码，通过设置去哪里获取用户的信息以及权限信息之后，交由springsecurity认证授权
        auth.userDetailsService(myUserService).passwordEncoder(passwordEncoder());
    }

    // 过滤器链和过滤路径
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 登录设置
        http.formLogin()
                // 放行登陆路径
                .loginProcessingUrl("/login")
                // 登录成功处理
                .successHandler(authenticationSuccessHandler())
                // 登录失败处理
                .failureHandler(authenticationFailureHandler())
                .permitAll();
        // 其他请求全部需要进行认证
        http.authorizeRequests().anyRequest().authenticated();
        // 跨域
        http.cors();
        // 禁止跨域伪造
        http.csrf().disable();
    }

    // 登录成功后返回JSON数据
    AuthenticationSuccessHandler authenticationSuccessHandler(){
        return (request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            // 1. 登录成功需要给前端用jwt生成一个token返回过去
            // 生成token，传递一个map ， 需要authentication当中的权限信息和用户名存放到map当中
            Map<String, Object> map = new HashMap<>();
            // 2.从authentication拿取想要的数据
            User principal = (User) authentication.getPrincipal();
            // 获取到用户名
            String username = principal.getUsername();
            // 获取权限  需要强调的是在传递的map当中是不能存放Collection<GrantedAuthority>这个类型的，并且还不能存放密码进去，都会报错
            Collection<GrantedAuthority> authorities = principal.getAuthorities();
            // 使用JDK1.8新特性进行转换  stream流
            List<String> collect = authorities.stream()
                    .filter(item -> item.getAuthority() != null)
                    .map(item -> item.getAuthority()).collect(Collectors.toList());

            map.put("username",username);
            map.put("permission",collect);
            // 使用jwt生成一个token返回
            String token = JWTUtil.createToken(map);

            Result result = new Result(200,"登陆成功",token);
            String s = JSON.toJSONString(result);

            writer.print(s);
            writer.flush();
            writer.close();
        };
    }

    // 失败返回JSON数据
    AuthenticationFailureHandler authenticationFailureHandler(){
        return (request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();

            Result result = new Result(500,"登录失败",null);

            String s = JSON.toJSONString(result);

            writer.print(s);

            writer.flush();
            writer.close();
        };
    }
}
